include '../inc/diskio.inc'

; DiskIO API Handler (INT 23h)
; AH - Operation
;   00 - Convert LBA to CHS
;    AX - LBA
;    ---
;    CH - Cylinder
;    DH - Head
;    CL - Sector

ext_diskio_handler:
	pusha

	cmp ah, 0
	jmp .lbatochs

	jmp .end_nocom
.lbatochs:
	call lbatochs
	mov word [.cx], cx
	mov byte [.dh], dh
	popa
	mov cx, word [.cx]
	mov dh, byte [.dh]

.end_nocom:
	popa
	iret
	.cx dw 0
	.dh db 0


; Convert LBA to CHS
;
; AX - LBA address
; ---
; CH - Cylinder
; DH - Head
; CL - Sector
lbatochs:
    pusha
    push ax

    ; Cylinder and head
    xor dx, dx
    mov cx, word SECTORS
    div cx

    xor dx, dx
    mov cx, word HEADS
    div cx

    mov byte [.track], al
    mov byte [.head], dl

    ; Sectors
    pop ax
    mov cx, word SECTORS
    div cx
    inc dl ; Sectors start from 1
    mov byte [.sector], dl

    popa
    mov ch, [.track]
    mov dh, [.head]
    mov cl, [.sector]
    ret
    .track db 0
    .head db 0
    .sector db 0
